<?php
/**
 * Created by PhpStorm.
 * User: jungshen
 * Date: 2018/11/23
 * Time: 14:50
 */

namespace app\api\behavior;


use app\store\service\GoodsService;
use service\LogService;
use think\Db;
use think\Exception;

class Cron
{
    public function run(){
        $this->cancel_order();
    }
    /**
     * 自动取消订单
     * @author jungshen
     */
    private function cancel_order(){
        $cancel_order_second=30*60;
        if($cancel_order_second<=0)return false;
        //查询需要被去取消的订单
        $order_list=Db::name('store_order')
            ->where('status',1)
            ->where('is_pay',0)
            ->where('create_at','<',date('Y-m-d H:i:s',time()-$cancel_order_second))
            ->column('id,order_no,mid');
        $order_nos=implode(',',array_column($order_list,'order_no'));
        if($order_nos){
            //将这些订单全部取消
            Db::startTrans();
            try{
                //取消订单
                Db::name('store_order')
                    ->where('order_no','in',$order_nos)
                    ->setField('status',0);
                $order_goods=Db::name('store_order_goods')
                    ->where('order_no','in',$order_nos)
                    ->column('goods_id');
                $order_goods=array_unique($order_goods);
                foreach ($order_goods as $v){
                    //同步库存
                    GoodsService::syncGoodsStock($v);
                }
                //订单商品状态取消
                Db::name('store_order_goods')
                    ->where('order_no','in',$order_nos)
                    ->where('status',1)
                    ->setField('status',0);
                //同步库存
            }catch (Exception $e){
                Db::rollback();
                LogService::write('订单取消','订单取消失败：'.$e->getMessage());
            }
            Db::commit();
        }
    }
}